/**
 * ajax请求数据封装
 * @param obj - options
 * @contentType - 请求头
 * @method - 请求方法 ['GET', 'POST']
 * @url - 地址
 * @params - 数据
 * @token - token验证
 *
 * 例：
 * Xsync({
        method: 'GET',
        url: './lib/test.json',
        params: {id: 123},
        token: 'token-token'
    }).then(res => {
        console.log('then:', res);
    }).catch(err => {
        console.log('catch:', err);
    });
 */

import { Message } from 'meri-design';

export default ({
    method = 'GET', url, contentType = 'application/json', params = null, originResponse = false
}) => new Promise((resolve, reject) => {
    if (method !== 'GET' && method !== 'POST') {
        reject(new Error('Method has to be GET or POST!'));
        return;
    }

    const xhr = new XMLHttpRequest() || new ActiveXObject('Microsoft.XMLHTTP');
    xhr.open(method, url, true);
    if (method === 'POST') {
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');
    }

    xhr.setRequestHeader('Content-Type', contentType);
    // xhr.send(typeof params === 'string' ? `jsonString=${params}` : `jsonString=${JSON.stringify(params)}`);
    xhr.send(typeof params === 'string' ? params : JSON.stringify(params));

    xhr.onreadystatechange = () => {
        const { readyState, status, responseText } = xhr;
        if (readyState !== 4) return;
        if ((status >= 200 && status < 300) || status === 304) {
            const result = JSON.parse(responseText);
            if (originResponse) {
                resolve(result);
                return;
            }
            const { data } = result;
            resolve(data);
        } else {
            Message.error(status);
            reject(status);
        }
    };
});
